const Base = require("./base.js");

module.exports = class extends Base {
    /**
     * 获取主观题作答记录
     */
    async getZhuguanrRcordsAction() {
        const profession_no = this.post('profession_no');
        const course_no = this.post('course_no');


        const sql = "SELECT rec_no,tb_zhuguanrecords.que_no,question,context FROM tb_zhuguanrecords JOIN tb_question ON(tb_zhuguanrecords.que_no=tb_question.que_no) WHERE tb_zhuguanrecords.profession_no='" + profession_no + "' AND tb_zhuguanrecords.course_no='" + course_no + "' AND mark IS NULL;";
        const recordList = await this.model("zhuguanrecords").query(sql);

        return this.success({
            recordList: recordList
        });
    }

    async upDataZhuguanrRcordsAction() {
        const recordList = JSON.parse(this.post('recordList'));
        if (recordList !== '') {
            for (let i = 0; i < recordList.length; i++) {
                await this.model('zhuguanrecords').where({
                    que_no: recordList[i].que_no
                }).update({
                    mark: recordList[i].mark
                })
            }

            //写入成绩
            let sql = "SELECT profession_no,course_no,stu_no,SUM(mark) AS smark FROM tb_zhuguanrecords;";
            let markList = await this.model("zhuguanrecords").query(sql);

            for (let i = 0; i < markList.length; i++) {
                await this.model("mark").where({
                    profession_no: markList[i].profession_no,
                    course_no: markList[i].course_no,
                    student_no: markList[i].stu_no
                }).update({
                    total3: markList[i].smark
                });

                //没有写入成绩的计0分
                await this.model("zhuguanrecords").where({
                    mark: null
                }).update({
                    mark: 0
                });

                //主观题得分算出后，可以计算总分
                let sql_2 = "SELECT *,total1+total2+total3  AS total FROM tb_mark WHERE profession_no='" + markList[i].profession_no + "' AND course_no='" + markList[i].course_no + "';";
                let totals = await this.model('mark').query(sql_2);

                for (let i = 0; i < totals.length; i++) {
                    await this.model('mark').where({
                        student_no: totals[i].student_no,
                        profession_no: totals[i].profession_no,
                        course_no: totals[i].course_no
                    }).update({
                        total: totals[i].total
                    });
                }
            }
        } else {
            return this.fail({
                code: 101
            })

        }

        return this.success({
            code: 100
        });
    }

}